package pikasial.images.traitements;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class RescaleTraitement implements Traitement {
	public static final int TYPE_NEAREST_NEIGHBOR = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
	public static final int TYPE_BILINEAR = AffineTransformOp.TYPE_BILINEAR;
	public static final int TYPE_BICUBIC = AffineTransformOp.TYPE_BICUBIC;

    protected double scaleHorizontal;
    protected double scaleVertical;
    protected BufferedImage source;
    protected int methode;

    public RescaleTraitement(final BufferedImage bi, final double scH, final double scV) {
        this(bi,scH,scV,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    }

    public RescaleTraitement(final BufferedImage bi, final double scH,
        final double scV, final int mode) throws IllegalArgumentException {
        if (mode != AffineTransformOp.TYPE_BICUBIC
            && mode != AffineTransformOp.TYPE_BILINEAR
            && mode != AffineTransformOp.TYPE_NEAREST_NEIGHBOR) {
            throw new IllegalArgumentException(
                "L'argument mode doit être une des trois valeurs"
                + " TYPE_NEAREST_NEIGHBOR, TYPE_BICUBIC, TYPE_BILINEAR de la classe"
                + " AffineTransformOp !");
        }

        scaleHorizontal = scH;
        scaleVertical = scV;
        source = bi;
        methode = mode;
    }

    public BufferedImage executeTraitement() {
        int w = source.getWidth();
        int h = source.getHeight();
        AffineTransform at = new AffineTransform();
        at.scale(scaleHorizontal, scaleVertical);
        AffineTransformOp op = new AffineTransformOp(
            at, methode);
        int imgType = source.getType();
        BufferedImage bImage = new BufferedImage(
            (int) (w * scaleHorizontal), (int) (h * scaleVertical), (imgType==BufferedImage.TYPE_CUSTOM)?BufferedImage.TYPE_INT_ARGB:imgType);
        return op.filter(source, bImage);

    }

    @Deprecated
    public static final ImageIcon rescaleToFitPanel(
        	BufferedImage bImage, int largeurPanel, int hauteurPanel) {
    	ImageIcon icon = null;
    	double rapportHL = ((double) bImage.getWidth()) / bImage.getHeight();

        double sc;
        if (rapportHL >= 1.0) {
            sc = ((double) largeurPanel) / bImage.getWidth();
        } else {
            sc = ((double) hauteurPanel) / bImage.getHeight();
        }
        if (sc < 1) {
            RescaleTraitement rt = new RescaleTraitement(bImage, sc, sc);
            icon = new ImageIcon(rt.executeTraitement());
        } else {
            icon = new ImageIcon(bImage);
        }
        return icon;
    }

	public BufferedImage undoChanges() {
		return source;
	}
}
